package com.dcits.test;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

public class App
{
    final static String cfn = "org.postgresql.Driver";
    final static String url = "jdbc:postgresql://192.168.10.104:5432/postgres";
    final static String user = "postgres";
    final static String pwd = "123456";

    public static void main(String[] args) {
        if(args.length == 2){
            String tableNmae = args[0];
            int size = Integer.parseInt(args[1]);
            Thread t1 =  new Thread(new Query(tableNmae,size));
            t1.setName(tableNmae);
            t1.start();
        }
    }


    static class Query  implements Runnable{
        private String tableName = "";
        private int n = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public Query(String tableName, int n) {
            this.tableName = tableName;
            this.n = n;
        }

        @Override
        public void run() {
            Connection con = null;
            Statement statement = null;
            ResultSet res = null;
            while(true) {
                try {
                    Class.forName(cfn);
                    con = DriverManager.getConnection(url, user, pwd);
                    statement = con.createStatement();
                    res = statement.executeQuery("select count(1) from " + tableName);
                    if (res.next()) {
                        int i = res.getInt(1);
                        System.out.println(i+"-------------"+sdf.format(new Date()));
                        if (i < n) {
                            Thread.sleep(1000 * 30);
                        } else {
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (res != null) res.close();
                        if (statement != null) statement.close();
                        if (con != null) con.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }
    }
}
